#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>

#define THRNUM 20
#define FNAME "/tmp/out"
#define LINESIZE 1024
static void *thread_add(void *p);
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int main(int argc, char **argv)
{
    pid_t pid;
    int i;
    int err;
    pthread_t tid[THRNUM];
    for (i = 0; i <= THRNUM; i++)
    {
        err = pthread_create(tid + i, NULL, thread_add, NULL);
        if (err > 0)
        {
            fprintf(stderr, "pthread create error\n");
            exit(1);
        }
    }

    for (i = 0; i <= THRNUM; i++)
    {
        pthread_join(tid[i],NULL);
    }
    pthread_mutex_destroy(&mutex);
    exit(0);
}

static void *thread_add(void *p)
{
    FILE *fd;
    char linebuf[LINESIZE];
    fd = fopen(FNAME, "r+");
    if(fd == NULL)
    {
        perror("fopen()");
        exit(1);
    }
    pthread_mutex_lock(&mutex);
    fgets(linebuf, LINESIZE, fd);
    fseek(fd, 0, SEEK_SET);
    //sleep(1);
    fprintf(fd, "%d\n", atoi(linebuf)+1);
    fclose(fd);
    pthread_mutex_unlock(&mutex);
    pthread_exit(p);
}
